# -*- coding: UTF-8 -*-
__author__ = "lishang"
__date__ = "$2021-5-18 9:39:02$"
__version__="1.0.0"

#from picmap.gui import *
import picmap.gui
import picmap.db
import picmap.pic
import picmap.map
import picmap.net
import picmap.unilGps
import os,time,sys,ctypes,re,signal,multiprocessing
from dateutil.parser import parse as strtotime
import webbrowser
#if(sys.version[:1] == "3"):import _thread as thread
#else:import thread

q = multiprocessing.Queue()         #进程通信队列
ppid=os.getpid()      #父类id
#xW=None          #当前窗口句柄

#脱离死循环 信号处理 临时任务  
#进程id ，信号发生时进程栈的状况
def gui_do(func, params=[]):
    print("guid_do: %s,%s" % (func,params))
    q.put([func,params])
    pass
# signal.signal(signal.SIGUSR1,gui_do)   

def start():
      #图片信息获取
#    tags={}
#    [x,y]=pic.getpos("./IMG_20160107_125703.jpg",tags)
#    print(map.get_city_info((x,y)))
#    exit()
    # print(map.getPoints({'zoom': '12', 'range': '22.35753176694853,22.69670762763039,113.87525736951248,114.24780263048748'}))
    # exit()

    newPid=os.fork()
    if newPid==0 :
        httpd=net.HttpServer(8066,'./picmap/html')
        httpd.application=map.application
        webbrowser.open('http://localhost:8066/bmap.html')
        httpd.start()
    else:
       ppid=0
       xW=gui.window(q)
       xW.start()
       print("kill to %s" %newPid)
       os.kill(newPid,signal.SIGQUIT) 
    print("bye!")
    
def echo(msg):
    gui.setStatusBar(msg)
    
def searchPic(path,refrash=False):
    pinfo=picmap.db.queryOne('path',"path='%s'" % path)
    if refrash: 
        pinfo['uptime']=0
        db.delete("pic","pid='%s'" % pinfo['id'])
    n=0
    for file in fileFind(path,r".+\.jpg",pinfo['uptime']): 
        tags={}
        try:
            [x,y]=pic.getpos(file,tags)
            echo("找到图片:%s,%s,%s" %(file,x,y))
            t=time.localtime(strtotime(tags['DateTimeOriginal']).timestamp())
            city=map.get_city_info((x,y))
        except Exception as e:
            echo("丢弃图片:%s(%s)" % (file,str(e)))
            continue

        pid=pinfo['id']
        db.insert("pic",{
            'pid':pid,
            'x':x,
            'y':y,
            'file':file[len(path):],
            'time':time.strftime("%Y年 %m月 %d日 %H时",t), #time.localtime(os.stat(file).st_ctime)
            "name":city,#ags['']
        })
        n+=1
    echo('更新完成')
    return n

#https://www.cnblogs.com/frisk/p/11567175.html,  https://www.cnblogs.com/amengduo/p/9586373.html, https://www.jb51.net/article/139018.htm
def fileFind(path,match=r'.+',time=0):
    for home, dirs, files in os.walk(path):
        #fnmatch.filter(files,match)
        for filename in files:  
            fullname = os.path.join(home, filename)
            if not re.match(match,filename):
                continue
            if time and os.stat(fullname).st_mtime < time:
                continue
            yield fullname 
            
            
def filterOption(all):
    tree={'name':{},'time':{},'path':{},'current':{'name':'','time':'','path':''}}
    for v in all:
        for k in ['name','time','path']:
            p=tree[k]
            for kk in v[k].split(" "):
                if p.get(kk) :
                    p=p[kk] 
                else :
                    p[kk]={}
                    p=p[kk]
    for k in ['name','time','path']:
            p=tree[k]
            while len(p) ==1: 
                kk=tuple(p.keys())[0]
                p=p[kk]
                tree['current'][k] += kk+" "
            tree[k+'List']=list(p.keys())

    return ({'name':tree['nameList'],'time':tree['timeList'],"path":tree['pathList']},tree['current'])
